#include "searchdialog.h"
#include "ui_searchdialog.h"
#include "yrmainwindow.h"
QList<QPair<QCheckBox*, QLineEdit*>> searchPairsA;
QList<QPair<QCheckBox*, QLineEdit*>> searchPairsB;
QList<QPair<QCheckBox*, QLineEdit*>> searchPairsC;
SearchDialog::SearchDialog(QSqlDatabase& db, YRMainWindow *parent) :
    ui(new Ui::SearchDialog), yrDatabase(db), mainWindow(parent)
{
    ui->setupUi(this);

    init();
}

SearchDialog::~SearchDialog()
{
    searchPairsA.clear();
    searchPairsB.clear();
    searchPairsC.clear();

    delete ui;
}

void SearchDialog::init() {

    searchPairsA.append(qMakePair(ui->checkBox_1, ui->lineEdit_TestID));
    searchPairsA.append(qMakePair(ui->checkBox_2, ui->lineEdit_Standard_used));
    searchPairsA.append(qMakePair(ui->checkBox_3, ui->lineEdit_Heat_flux));
    searchPairsA.append(qMakePair(ui->checkBox_4, ui->lineEdit_Sample_description));
    searchPairsA.append(qMakePair(ui->checkBox_5, ui->lineEdit_Material_name_ID));
    searchPairsA.append(qMakePair(ui->checkBox_6, ui->lineEdit_Specimen_number));

    searchPairsB.append(qMakePair(ui->checkBox_7, ui->lineEdit_Thickness));
    searchPairsB.append(qMakePair(ui->checkBox_8, ui->lineEdit_Time_to_ignition));
    searchPairsB.append(qMakePair(ui->checkBox_9, ui->lineEdit_Time_to_flameout));
    searchPairsB.append(qMakePair(ui->checkBox_10, ui->lineEdit_Ignition_to_flameout));

    searchPairsC.append(qMakePair(ui->checkBox_11, ui->lineEdit_peak_HRR));
    searchPairsC.append(qMakePair(ui->checkBox_12, ui->lineEdit_peak_EHC));
    searchPairsC.append(qMakePair(ui->checkBox_13, ui->lineEdit_peak_MLR));
    searchPairsC.append(qMakePair(ui->checkBox_14, ui->lineEdit_peak_SEA));
    searchPairsC.append(qMakePair(ui->checkBox_15, ui->lineEdit_peak_COY));
    searchPairsC.append(qMakePair(ui->checkBox_23, ui->lineEdit_peak_CO2Y));

    searchPairsC.append(qMakePair(ui->checkBox_21, ui->lineEdit_t_peak_HRR));
    searchPairsC.append(qMakePair(ui->checkBox_22, ui->lineEdit_t_peak_EHC));
    searchPairsC.append(qMakePair(ui->checkBox_29, ui->lineEdit_t_peak_MLR));
    searchPairsC.append(qMakePair(ui->checkBox_16, ui->lineEdit_t_peak_SEA));
    searchPairsC.append(qMakePair(ui->checkBox_24, ui->lineEdit_t_peak_COY));
    searchPairsC.append(qMakePair(ui->checkBox_18, ui->lineEdit_t_peak_CO2Y));

    searchPairsC.append(qMakePair(ui->checkBox_17, ui->lineEdit_Total_heat_release));
    searchPairsC.append(qMakePair(ui->checkBox_25, ui->lineEdit_Total_oxygen_consumed));
    searchPairsC.append(qMakePair(ui->checkBox_26, ui->lineEdit_Mass_lost));
    searchPairsC.append(qMakePair(ui->checkBox_20, ui->lineEdit_Average_specific_MLR));
    searchPairsC.append(qMakePair(ui->checkBox_27, ui->lineEdit_Total_smoke_release));
    searchPairsC.append(qMakePair(ui->checkBox_30, ui->lineEdit_Total_smoke_production));
    searchPairsC.append(qMakePair(ui->checkBox_28, ui->lineEdit_MARHE));
}

void SearchDialog::on_pushButton_A_clicked()
{
    // 如果勾选数量超过11个，显示警告并返回
    if (countCheckedItems() >= 11) {
        QMessageBox::warning(
                    this, // 使用当前对话框作为父窗口
                    "查询限制",
                    "为了保证查询效率，最多只能选择10个条件进行查询。"
                    );
        return;
    }

    QStringList subqueries; // 用于存储每个条件的子查询
    for (const auto &pair : searchPairsA) {
        QString keyword = pair.second->text();
        if (pair.first->isChecked() && !keyword.isEmpty()) {
            QString infoName = pair.first->text().contains("试验编号") ? "TestID" :
                               pair.first->text().contains("危险分级") ? "Risk level" :
                               pair.first->text().contains("辐射热流强度(kW/㎡)") ? "Heat flux" :
                               pair.first->text().contains("引燃方法") ? "Ignition method" :
                               pair.first->text().contains("试样材料名称/ID") ? "Material name" :
                               "Material type";
            // 使用反引号包围字段名，并构建子查询
            QString subquery = QString("(SELECT `TestID` FROM `TestInfo` WHERE `InfoName` LIKE '%%1%' AND `InfoValue` LIKE '%%2%')").arg(infoName).arg(keyword);
            subqueries.append(subquery);
        }
    }

    for (const auto &pair : searchPairsB) {
        QStringList rangeParts = pair.second->text().split('-');
        if (pair.first->isChecked() && !rangeParts.isEmpty()) {
            if (rangeParts.size() < 2) {
                QMessageBox::warning(
                    nullptr, // 父窗口（若无则设为nullptr）
                    "格式检查警告", // 对话框标题
                    QString("请检查待查内容【%1】的格式").arg(pair.first->text())  // 提示信息
                );
                return;
            }
            QString infoName = pair.first->text().contains("试样厚度(mm)") ? "Thickness" :
                               pair.first->text().contains("引燃时间(s)") ? "Time to ignition" :
                               pair.first->text().contains("熄灭时间(s)") ? "Time to flameout" :
                               "Ignition to flameout";
            // 使用反引号包围字段名，并构建子查询
            QString subquery = QString("(SELECT `TestID` FROM `TestInfo` WHERE `InfoName` LIKE '%%1%' AND CAST(`InfoValue` AS DECIMAL(10,2)) BETWEEN '%2' AND '%3')")
                    .arg(infoName).arg(rangeParts[0].trimmed()).arg(rangeParts[1].trimmed());
            subqueries.append(subquery);
        }
    }

    for (const auto &pair : searchPairsC) {
            QStringList rangeParts = pair.second->text().split('-');
            if (pair.first->isChecked() && !rangeParts.isEmpty()) {
                if (rangeParts.size() < 2) {
                    QMessageBox::warning(
                        nullptr, // 父窗口（若无则设为nullptr）
                        "格式检查警告", // 对话框标题
                        QString("请检查待查内容【%1】的格式").arg(pair.first->text())  // 提示信息
                    );
                    return;
                }
                QString infoName = pair.first->text().contains("最大热释放速率(kW/㎡)") ? "peak HRR (kW/㎡)" :
                                   pair.first->text().contains("最大有效燃烧热(MJ/kg)") ? "peak EHC (MJ/kg)" :
                                   pair.first->text().contains("最大质量损失速率(g/s)") ? "peak MLR (g/s)" :
                                   pair.first->text().contains("最大比消光面积(㎡/kg)") ? "peak SEA (㎡/kg)" :
                                   pair.first->text().contains("最大CO生成率(kg/kg)") ? "peak COY (kg/kg)" :
                                   pair.first->text().contains("最大CO2生成率(kg/kg)") ? "peak CO2Y (kg/kg)" :
                                   pair.first->text().contains("达到最大热释放速率的时间(s)") ? "t peak HRR (s)" :
                                   pair.first->text().contains("达到最大有效燃烧热的时间(s)") ? "t peak EHC (s)" :
                                   pair.first->text().contains("达到最大质量损失的时间(s)") ? "t peak MLR (s)" :
                                   pair.first->text().contains("达到最大比消光面积的时间(s)") ? "t peak SEA (s)" :
                                   pair.first->text().contains("达到最大CO生成率的时间(s)") ? "t peak COY (s)" :
                                   pair.first->text().contains("达到最大CO2生成率的时间(s)") ? "t peak CO2Y (s)" :
                                   pair.first->text().contains("总热释放量(MJ/㎡)") ? "Total heat release" :
                                   pair.first->text().contains("总耗氧量(g)") ? "Total oxygen consumed" :
                                   pair.first->text().contains("质量损失(g)") ? "Mass lost" :
                                   pair.first->text().contains("单位面积平均质量损失速率(g/(s•㎡))") ? "Average specific MLR" :
                                   pair.first->text().contains("单位面积总产烟量(㎡/㎡)") ? "Total smoke release" :
                                   pair.first->text().contains("总产烟量(㎡)") ? "Total smoke production" :
                                   "MARHE (kW/㎡)";
                // 使用反引号包围字段名，并构建子查询
                QString subquery = QString("(SELECT `TestID` FROM `TestResults` WHERE `ResultName` LIKE '%%1%' AND CAST(`ResultValue` AS DECIMAL(10,2)) BETWEEN '%2' AND '%3')")
                        .arg(infoName).arg(rangeParts[0].trimmed()).arg(rangeParts[1].trimmed());
                subqueries.append(subquery);
            }
        }


    QSqlQuery query(yrDatabase);

    // 修改点：根据subqueries的数量来构建SQL语句
    QString sqlQuery;
    if (subqueries.isEmpty()) {
        // 如果没有条件，可以返回空结果或者所有结果，根据需求决定
        sqlQuery = "SELECT DISTINCT `TestID` FROM `TestInfo` ORDER BY `id` ASC";
    } else {
        // 如果有多个条件，使用AND连接每个子查询
        QString whereClause = subqueries.join(" AND `TestID` IN ");
        sqlQuery = QString("SELECT DISTINCT `TestID` FROM `TestInfo` WHERE `TestID` IN %1 ORDER BY `id` ASC").arg(whereClause);
    }

    if (ui->checkBox_1->isChecked() && !ui->lineEdit_TestID->text().isEmpty()) {
        sqlQuery = QString("SELECT DISTINCT `TestID` FROM `TestInfo` WHERE `TestID` LIKE '%%1%' ORDER BY `id` ASC").arg(ui->lineEdit_TestID->text());
    }

    if (ui->checkBox_1->isChecked() && ui->lineEdit_TestID->text().isEmpty()) {
        sqlQuery = "SELECT DISTINCT `TestID` FROM `TestInfo` ORDER BY `id` ASC";
    }

    mainWindow->loadTestIDsToTreeWidget(sqlQuery, true);
    mainWindow->update_count();

    qDebug() << sqlQuery;
}

void SearchDialog::cleanAll() {
    // 阻塞信号，避免多次触发更新
    //QSignalBlocker blocker(this);

    auto cleanPair = [](const QPair<QCheckBox*, QLineEdit*>& pair) {
        if (pair.first->isChecked()) {
            pair.first->setCheckState(Qt::Unchecked);
        }
        if (!pair.second->text().isEmpty()) {
            pair.second->setText("");
        }
    };

    // 清理所有组
    for (const auto &pair : searchPairsA) cleanPair(pair);
    for (const auto &pair : searchPairsB) cleanPair(pair);
    for (const auto &pair : searchPairsC) cleanPair(pair);
}

void SearchDialog::on_pushButton_B_clicked()
{
    cleanAll();
}

int SearchDialog::countCheckedItems() const {
    int count = 0;
    for (const auto &pair : searchPairsA) {
        if (pair.first->isChecked()) count++;
    }
    for (const auto &pair : searchPairsB) {
        if (pair.first->isChecked()) count++;
    }
    for (const auto &pair : searchPairsC) {
        if (pair.first->isChecked()) count++;
    }
    return count;
}

void SearchDialog::updateCheckBoxStates() {
    int checked = countCheckedItems();
    bool enableOthers = checked < 10;

    auto setEnabled = [enableOthers](QCheckBox* cb, bool isChecked) {
        cb->setEnabled(enableOthers || isChecked);
    };

    for (const auto &pair : searchPairsA) setEnabled(pair.first, pair.first->isChecked());
    for (const auto &pair : searchPairsB) setEnabled(pair.first, pair.first->isChecked());
    for (const auto &pair : searchPairsC) setEnabled(pair.first, pair.first->isChecked());
}

void SearchDialog::onCheckBoxStateChanged()
{
    if (!ui->label) return;

    ui->label->setText(QString("已选: %1/10").arg(countCheckedItems()));
    updateCheckBoxStates();

    if (countCheckedItems() == 10) {
        QMessageBox::warning(
            this,
            "查询提示",
            "为了保证查询效率，最多选择10个条件进行查询。"
        );
    }
}
